import sys
import os
sys.path.append(os.path.abspath(os.path.dirname(__file__)) + "/..")
import urllib.request
import json
import time
import pandas as pd
import matplotlib.pyplot as plt
from stock.stock_utils import *
from utils.smtp.smtp import *

cycle = 5
num = 100
lk = 0xff
ld = 0xff
lj = 0xff
kdj_min = 20
kdj_max = 80

def monitor_kdj_data(df, code):
    global lk, ld, lj
    k = df["K"][-1:].iloc[0]
    d = df["D"][-1:].iloc[0]
    j = df["J"][-1:].iloc[0]
    # print(df)
    print("k=", k, "d=", d, "j=", j, "now", get_time())
    if lk == k and ld == d and lj == j:
        print("is same")
        return
    # 逻辑是kdj值出入20或80时做报警
    ca = []
    ca.append({"last":lj, "cur":j, "val":kdj_min, "desc":"j"})
    ca.append({"last":lk, "cur":k, "val":kdj_min, "desc":"k"})
    ca.append({"last":lj, "cur":j, "val":kdj_max, "desc":"j"})
    ca.append({"last":lk, "cur":k, "val":kdj_max, "desc":"k"})
    llj = lj
    lk = k
    ld = d
    lj = j
    # print("llj=", llj)
    if llj == 0xff:
        smtp = Smtp()
        smtp.Send(
                "goto stock monitor %s"%(code)
            )
        print("monitor begin")
        return
    
    for v in ca:
        # print(v)
        if v["last"] < v["val"] and v["cur"] >= v["val"]:
            smtp = Smtp()
            smtp.Send(
                "%s %s change from %f to %f limit %f" % (code, v["desc"], v["last"], v["cur"], v["val"])
            )
            print("smtp *******************")
            break
        if v["last"] > v["val"] and v["cur"] <= v["val"]:
            smtp = Smtp()
            smtp.Send(
                "%s %s change from %f to %f limit %f" % (code, v["desc"], v["last"], v["cur"], v["val"])
            )
            print("smtp *******************")
            break        

def monitor_code(code):
    # 判断下时间
    if work_time_check() == False:
        # print("err time")
        return
    data = get_url_data(get_url(code, cycle, num))
    # 转换dataframe
    kdj = get_kdj_data(data)
    # 监控kdj参数
    monitor_kdj_data(kdj, code)
def monitor():
    # monitor_code("sz000568")
    while True:
        monitor_code("sz000568")
        time.sleep(60)


if __name__ == "__main__":
    monitor()
    